//
//  BHStadiumlistViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/1.
//  场馆列表

import UIKit

class BHStadiumlistViewController: BHBaseViewController {
    lazy var filterHeaderView: BHCompetitionFilterView = {
        let view = BHCompetitionFilterView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: BHCompetitionFilterView.headerHeight)
        view.hideItemIndex = 3
        view.delegate = self
        return view
    }()
    lazy var navigationBarView: BHStadiumlistNavigationBar = {
        let view = BHStadiumlistNavigationBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.begainY)
        view.delegate = self
        return view
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.sectionInset = .zero
        let view = UICollectionView.buildCollectionView(layout: layout)
        view.frame = CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.showHeight-BHCompetitionFilterView.headerHeight)
        view.register(UINib.init(nibName: "BHSportAndPlaceCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BHSportAndPlaceCollectionViewCell")
        view.register(BHGameBannerCell.self, forCellWithReuseIdentifier: "BHGameBannerCell")
        view.backgroundColor = .white
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var classFilterView: BHCompetitionDoubleView = {
        let view = BHCompetitionDoubleView.init(type: 0)
        view.frame = CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY)
        view.delegate = self
        return view
    }()
   
    lazy var areaFilterView: BHCompetitionSortView = {
        let view = BHCompetitionSortView.init(frame: CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY))
        view.delegate = self
        return view
    }()
    
    lazy var sortFilterView: BHCompetitionSortView = {
        let view = BHCompetitionSortView.init(frame: CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY))
        view.delegate = self
        view.itemArray = BHHomeCityModel.sortStadiumArray
        return view
    }()
    
    lazy var serviceManager: BHStadiumServiceManager = {
        let manager = BHStadiumServiceManager.init()
        return manager
    }()
    
    lazy var bannerCell: BHGameBannerCell = { [unowned self] in
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHGameBannerCell", for: IndexPath.init(row: 0, section: 0)) as! BHGameBannerCell
        return cell
        
    }()
    fileprivate var currentType: Int = 0
    fileprivate var stadiumArray: [BHCommonStadiumModel] = []
    fileprivate var bannerArray: [BHCommonBannerModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.removeFromSuperview()
        self.view.addSubview(self.collectionView)
        self.view.addSubview(self.filterHeaderView)
        self.view.addSubview(self.navigationBarView)
        
        self.view.addSubview(self.classFilterView)
        self.view.addSubview(self.areaFilterView)
        self.view.addSubview(self.sortFilterView)
        
        self.navigationBarView.backBtn.addBtnAction(action: {[weak self] (_) in
            self?.navigationController?.popViewController(animated: true)
        }, for: .touchUpInside)
        
        
        self.queryFilterTypeService(model: nil)
        self.queryCityAreaService()
        self.queryBannerService()
        self.queryResultOberserve()
        self.serviceManager.queryStadiumListAllService()
        
        
        self.collectionView.addRefresh {[weak self] in
            self?.page = 1
            self?.serviceManager.pageNo = 1
            self?.serviceManager.queryStadiumListAllService()
        }
        
        self.collectionView.addloadMore {[weak self] in
            self?.page += 1
            self?.serviceManager.pageNo = self?.page ?? 1
            self?.serviceManager.queryStadiumListAllService()
        }
       
    }
    
}
// 切换筛选条件的点击
extension BHStadiumlistViewController: BHCompetitionFilterViewDelegate {
    func filterHeaderSearchForKey(key: String) { // 搜索
        self.serviceManager.searchKey = key
        
        self.collectionView.mj_header?.beginRefreshing()
    }
    
    func filterHeaderDidChose(sender: UIButton) {
        let index = sender.tag-100
        self.classFilterView.showOrHide(show: index == 0)
        self.areaFilterView.showOrHide(show: index == 1)
        self.sortFilterView.showOrHide(show: index == 2)
    }
    
    func fitterHeaderBegainSearch() {
        self.classFilterView.showOrHide(show: false)
        self.areaFilterView.showOrHide(show: false)
        self.sortFilterView.showOrHide(show: false)
        
        self.filterHeaderView.resetAllState()
    }
  
}

extension BHStadiumlistViewController: BHCompetitionSortViewDelegate,BHCompetitionDoubleViewDelegate {
    
    // MARK:切换类型的代理
    func didChoseLeft(model: BHCommonSortTypeModel) {
        self.queryFilterTypeService(model: model)
        
    }
    func didChoseRight(model: BHCommonSortTypeModel) {
        self.serviceManager.typeOneValue = model.parentId
        self.serviceManager.typeTwoValue = model.typeId
       
        self.filterHeaderView.changeIndexBtnText(index: 0, text: "\(model.text) ")
        self.collectionView.mj_header?.beginRefreshing()
    }
    func didTypeChoseClose() {
        self.filterHeaderView.resetAllState()
    }
    
    //区域和排序
    func didSortChoseIndex(model: BHHomeCityModel?, index: Int, view: BHCompetitionSortView) {
        if view == self.areaFilterView {
            self.serviceManager.regionName = model?.name ?? "南京"
            self.filterHeaderView.changeIndexBtnText(index: 1, text: "\(self.serviceManager.regionName) ")

        }else {
            self.serviceManager.sort = model?.code ?? "1"
            self.filterHeaderView.changeIndexBtnText(index: 2, text: "\(model?.name ?? "排序") ")
        }
        
        self.collectionView.mj_header?.beginRefreshing()
    }
    
    func didSortViewClose() {
        self.filterHeaderView.resetAllState()
    }
}

extension BHStadiumlistViewController: BHStadiumlistNavigationBarDelagete {
    func didStadiumNavigationBarSelectIndex(index: Int) {
        self.page = 1
        self.serviceManager.pageNo = 1
        self.currentType = index
        self.serviceManager.type = index+1
        
        self.collectionView.mj_header?.beginRefreshing()
    }
}

extension BHStadiumlistViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            if self.bannerArray.count == 0 {
                return 0
            }
            return 1
        }
        return self.stadiumArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            if self.bannerArray.count == 0 {
                return .zero
            }
            return CGSize(width: UIScreen.width, height: BHGameBannerCell.cellHeight)
        }
        let model = self.stadiumArray[indexPath.row]
        return CGSize(width: UIScreen.width, height: model.cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            let model = self.stadiumArray[indexPath.row]
            BHRouter.shared.bh_goStadiumDetail(stadium: model.stadiumId)
        }
    }
}

extension BHStadiumlistViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            return self.bannerCell
        }else {
            let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHSportAndPlaceCollectionViewCell", for: indexPath) as! BHSportAndPlaceCollectionViewCell
            let model = self.stadiumArray[indexPath.row]
            cell.model = model
            return cell
        }
    }
    
}


extension BHStadiumlistViewController {
    func queryResultOberserve()  {
        self.serviceManager.responseForMainStadiumListBlock = {[weak self] (success,errorMsg,total,array) in
            self?.collectionView.endRefresh()
            self?.collectionView.endLoading()
            if success == true {
                if self?.page == 1 {
                    self?.collectionView.endLoadWithNoMoreData(false)
                    if self?.stadiumArray.count != 0 {
                        self?.stadiumArray.removeAll()
                    }
                }
                
                self?.stadiumArray.append(contentsOf: array)
                self?.collectionView.reloadData()
                if self?.stadiumArray.count ?? 0 >= total {
                    self?.collectionView.endLoadWithNoMoreData(true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    
    }
    
    func queryBannerService() {
        BHCommonService.queryBannerService(type: 2) {[weak self] (array) in
            self?.bannerArray = array
            self?.bannerCell.banner = array
            self?.collectionView.reloadData()
        }
    }
    
    
    func queryFilterTypeService(model: BHCommonSortTypeModel?)  {
        if model == nil {
            BHCommonService.queryTypeOneService(type: 1) { (modelArray) in
                self.classFilterView.leftArray = modelArray
            }
        }else {
            BHCommonService.queryTypeTwoService(parentModel: model!) { (array) in
                model?.childArray = array
                self.classFilterView.rightTable.reloadData()
            }
        }
    }
    
    func queryCityAreaService()  {
        BHCommonService.queryCityAreaService(cityName: nil) { (areaArray) in
    
            self.areaFilterView.itemArray = areaArray
            
        }
    }
}
